<?php

namespace App\Console\Commands;

use App\Models\ActivitySale;
use App\Models\Marketing;
use App\Models\User;
use App\Models\UserAccount;
use App\Models\UserReward;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MarketingUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'marketing.marketing_user';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '优惠券发放';

    /**
     * 一次发放最大量
     * @var int
     */
    protected $number = 1000;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $redis = app('redis.connection');
        $redisList = $redis->rpop('marketing');
        if (!$redisList){
            w_log('没有要发放的优惠券' ,'marketing');
            return '没有要发放的优惠券';
        }
        $redisList = json_decode($redisList, true);
        $marketing = Marketing::find($redisList['id']);
        $activitySale = ActivitySale::find($marketing->activity_sale_id);
        $type = $redisList['type'];
        $page = $redisList['page'];
        $offset = ($page-1)*$this->number;
        switch ($type) {
            case 1:
                $value = explode(',', $marketing->scope);
                $user_number = User::whereIn('id', $value)->count('id');
                $user_list = User::whereIn('id', $value)->offset($offset)->limit($this->number)->get();
                $number = ceil($user_number/$this->number);
                break;
            case 2:
                $value = explode(',', $marketing->scope);
                $user_number = UserAccount::whereIn('user_level_id', $value)->count('id');
                $user_list = UserAccount::whereIn('user_level_id', $value)->offset($offset)->limit($this->number)->get();
                $number = ceil($user_number/$this->number);
                break;
            case 3:
                $user_number = User::count('id');
                $user_list = User::offset($offset)->limit($this->number)->get();
                $number = ceil($user_number/$this->number);
                break;
            default:
                return false;
        }

        if (!is_null($user_list[0]) ){
            foreach ($user_list as $item => $value) {
                $data[$item]['user_id'] = ($type == 2 ? $value['user_id'] : $value['id']);
                $data[$item]['activity_sale_id'] = $marketing->activity_sale_id;
                $data[$item]['card_name'] = $marketing->activity_name;
                $data[$item]['type_source'] = 1;
                $data[$item]['full'] = $activitySale->full??0;
                $data[$item]['money'] = $activitySale->less??0;
                $data[$item]['time_end_valid'] = strtotime($activitySale->end_at);
                $data[$item]['time_start_valid'] = strtotime($activitySale->start_at);
                $data[$item]['created_at'] = date('Y-m-d h:m:s');
                $data[$item]['market_id'] = $marketing->id;
                Cache::store('redis')->forget('user:info_' . $data[$item]['user_id']);
            }
            try {
                DB::beginTransaction();
                $marketing->amount += count($user_list) ;
                $activitySale->amount += count($user_list) ;
                $marketing->status = ($redisList['page'] == $number && (count($user_list) <= $this->number) && ($redisList['number'] == $marketing->number)) ? Marketing::STATUS_TWO: Marketing::STATUS_ONE ;
                UserReward::insert($data);
                $marketing->save();
                $activitySale->save();
                DB::commit();
                w_log('优惠券脚本执行成功：【'.json_encode($redisList).'/' . $marketing->activity_name . '/' . $marketing->id . '】'. '/'.$redisList['number'].'-'.$number.'-'. $redisList['page'],'marketing');
                if ($redisList['page'] == $number && $redisList['number'] != $marketing->number){
                    $redis->rpush('marketing', json_encode(['type' => $redisList['type'], 'id' => $marketing->id, 'page' => 1, 'number' => ($redisList['number'] + 1)]));
                }elseif ($redisList['page'] != $number && $redisList['page'] < $number ){
                    $redis->rpush('marketing', json_encode(['type' => $redisList['type'],'id' => $marketing->id,  'page' => ($redisList['page'] + 1), 'number' => ($redisList['number'])]));
                }
                echo  '这次优惠券脚本执行完';
                return '这次优惠券脚本执行完';
            } catch (\Exception $e) {
                DB::rollBack();
                w_log('优惠券脚本执行错误：【' . json_encode($redisList) . '】' . $e->getMessage(),'marketing');
                $redis->lpush('marketing', json_encode($redisList));
                echo $e->getMessage();
            }
        }
        echo  '这次优惠券脚本执行完';
        return '这次优惠券脚本执行完';
    }
}
